package top.zywork.controller;

import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.dynamic.scaffold.TypeInitializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.zywork.annotation.AppAuthFilter;
import top.zywork.annotation.SysLog;
import top.zywork.common.*;
import top.zywork.constant.FileConstants;
import top.zywork.dos.DefaultDistributionConfig;
import top.zywork.dto.PagerDTO;
import top.zywork.dto.SysConfigDTO;
import top.zywork.enums.DatePatternEnum;
import top.zywork.enums.ResponseStatusEnum;
import top.zywork.enums.SysConfigEnum;
import top.zywork.enums.UploadTypeEnum;
import top.zywork.query.SysConfigQuery;
import top.zywork.service.SysConfigService;
import top.zywork.service.UploadService;
import top.zywork.vo.*;
import top.zywork.vo.goods.GoodsAttrConfig;

import java.util.List;

/**
 * SysConfigController控制器类<br/>
 *
 * 创建于2019-07-02<br/>
 *
 * @author http://zywork.top 王振宇
 * @version 1.0
 */
@RestController
@RequestMapping("/sys-config")
@AppAuthFilter(ignoreUrls = {
        "/sys-config/admin/upload-img"
})
@Slf4j
public class SysConfigController extends BaseController {

    @Value("${storage.provider}")
    private String storageProvider;

    @Value("${storage.local.compressSizes}")
    private String compressSizes;

    @Value("${storage.local.compressScales}")
    private String compressScales;

    @Value("${storage.local.sysPic.imgParentDir}")
    private String imgParentDir;

    @Value("${storage.local.sysPic.imgDir}")
    private String imgDir;

    @Value("${storage.local.sysPic.imgUrl}")
    private String imgUrl;

    @Value("${storage.local.sysPic.keepFileName}")
    private Boolean keepFileName;

    private SysConfigService sysConfigService;

    private UploadService uploadService;

    @PostMapping("admin/save")
    @SysLog(description = "后台保存SysConfigVO")
    public ResponseStatusVO save(@RequestBody @Validated SysConfigVO sysConfigVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        sysConfigService.save(BeanUtils.copy(sysConfigVO, SysConfigDTO.class));
        return ResponseStatusVO.ok("添加成功", null);
    }

    @PostMapping("admin/batch-save")
    @SysLog(description = "后台批量保存SysConfigVO")
    public ResponseStatusVO saveBatch(@RequestBody @Validated List<SysConfigVO> sysConfigVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        sysConfigService.saveBatch(BeanUtils.copyListObj(sysConfigVOList, SysConfigDTO.class));
        return ResponseStatusVO.ok("批量添加成功", null);
    }

    @GetMapping("admin/remove/{id}")
    @SysLog(description = "后台删除SysConfigVO")
    public ResponseStatusVO removeById(@PathVariable("id") Long id) {
        sysConfigService.removeById(id);
        return ResponseStatusVO.ok("删除成功", null);
    }

    @PostMapping("admin/batch-remove")
    @SysLog(description = "后台批量删除SysConfigVO")
    public ResponseStatusVO removeByIds(@RequestBody String[] ids) {
        sysConfigService.removeByIds(StringUtils.strArrayToLongArray(ids));
        return ResponseStatusVO.ok("批量删除成功", null);
    }

    @PostMapping("admin/update")
    @SysLog(description = "后台更新SysConfigVO")
    public ResponseStatusVO update(@RequestBody @Validated SysConfigVO sysConfigVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        int updateRows = sysConfigService.update(BeanUtils.copy(sysConfigVO, SysConfigDTO.class));
        if (updateRows == 1) {
            return ResponseStatusVO.ok("更新成功", null);
        } else {
            return ResponseStatusVO.dataError("数据版本号有问题，在此更新前数据已被更新", null);
        }
    }

    @PostMapping("admin/batch-update")
    @SysLog(description = "后台批量更新SysConfigVO")
    public ResponseStatusVO updateBatch(@RequestBody @Validated List<SysConfigVO> sysConfigVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        sysConfigService.updateBatch(BeanUtils.copyListObj(sysConfigVOList, SysConfigDTO.class));
        return ResponseStatusVO.ok("批量更新成功", null);
    }

    @PostMapping("admin/active")
    @SysLog(description = "后台激活或冻结SysConfigVO")
    public ResponseStatusVO active(@RequestBody SysConfigVO sysConfigVO) {
        sysConfigService.update(BeanUtils.copy(sysConfigVO, SysConfigDTO.class));
        return ResponseStatusVO.ok("激活或冻结成功", null);
    }

    @PostMapping("admin/batch-active")
    @SysLog(description = "后台批量激活或冻结SysConfigVO")
    public ResponseStatusVO activeBatch(@RequestBody @Validated List<SysConfigVO> sysConfigVOList) {
        sysConfigService.updateBatch(BeanUtils.copyListObj(sysConfigVOList, SysConfigDTO.class));
        return ResponseStatusVO.ok("批量激活或冻结成功", null);
    }

    @GetMapping("admin/one/{id}")
    public ResponseStatusVO getById(@PathVariable("id") Long id) {
        SysConfigVO sysConfigVO = new SysConfigVO();
        Object obj = sysConfigService.getById(id);
        if (obj != null) {
            sysConfigVO = BeanUtils.copy(obj, SysConfigVO.class);
        }
        return ResponseStatusVO.ok("查询成功", sysConfigVO);
    }

    @GetMapping("admin/all")
    public ResponseStatusVO listAll() {
        PagerDTO pagerDTO = sysConfigService.listAll();
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), SysConfigVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/all-cond")
    public ResponseStatusVO listAllByCondition(@RequestBody SysConfigQuery sysConfigQuery) {
        PagerDTO pagerDTO = sysConfigService.listAllByCondition(sysConfigQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), SysConfigVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/pager-cond")
    public ResponseStatusVO listPageByCondition(@RequestBody SysConfigQuery sysConfigQuery) {
        PagerDTO pagerDTO = sysConfigService.listPageByCondition(sysConfigQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), SysConfigVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    /**
     * 前端根据条件获取指定的配置
     * @param sysConfigQuery
     * @return
     */
    @PostMapping("any/pager-cond")
    public ResponseStatusVO anyListPageByCondition(@RequestBody SysConfigQuery sysConfigQuery) {
        // 只获取允许外部访问的记录
        sysConfigQuery.setOutsideAccess((byte) 1);
        return listPageByCondition(sysConfigQuery);
    }

    @GetMapping("any/distribution-config")
    public ResponseStatusVO getMallDistributionConfig() {
        DefaultDistributionConfig defaultDistributionConfig = sysConfigService.getByName(SysConfigEnum.DEFAULT_DISTRIBUTION_CONFIG.getValue(), DefaultDistributionConfig.class);
        return ResponseStatusVO.ok("查询成功", defaultDistributionConfig);
    }

    /**
     * 获取图片配置信息
     * @return
     */
    @GetMapping("any/pic-config")
    public ResponseStatusVO getPicConfig() {
        SysPicConfig sysPicConfig = sysConfigService.getByName(SysConfigEnum.SYS_PIC_CONFIG.getValue(), SysPicConfig.class);
        return ResponseStatusVO.ok("查询成功", sysPicConfig);
    }

    /**
     * 获取文字配置
     * @return
     */
    @GetMapping("any/txt-config")
    public ResponseStatusVO getTxtConfig() {
        SysTxtConfig sysTxtConfig = sysConfigService.getByName(SysConfigEnum.SYS_TXT_CONFIG.getValue(), SysTxtConfig.class);
        return ResponseStatusVO.ok("查询成功", sysTxtConfig);
    }

    /**
     * 获取商品属性配置
     * @return
     */
    @GetMapping("any/goods-attr-config")
    public ResponseStatusVO getGoodsAttrConfig() {
        GoodsAttrConfig goodsAttrConfig = sysConfigService.getByName(SysConfigEnum.GOODS_ATTR_CONFIG.getValue(), GoodsAttrConfig.class);
        return ResponseStatusVO.ok("查询成功", goodsAttrConfig);
    }

    /**
     * 上传图片资源文件
     * @param file
     * @return
     */
    @PostMapping("admin/upload-img")
    @SysLog(description = "后台上传配置图片", requestParams = false)
    public ResponseStatusVO uploadImg(MultipartFile file, String type) {
        String date = DateFormatUtils.format(DateUtils.currentDate(), DatePatternEnum.DATE.getValue());
        UploadUtils.UploadOptions uploadOptions = UploadUtils.UploadOptions.builder().uploadParentDir(imgParentDir).uploadDir(imgDir + FileConstants.SEPARATOR + date)
                .dbSaveUrl(imgUrl + FileConstants.SEPARATOR + date).keepFileName(keepFileName).build();
        uploadOptions.generateCompressSizes(compressSizes);
        ResponseStatusVO responseStatusVO = uploadService.uploadFile(storageProvider, file, UploadTypeEnum.IMAGE.getAllowedExts(), UploadTypeEnum.IMAGE.getMaxSize(), uploadOptions);
        if (ResponseStatusEnum.OK.getCode().equals(responseStatusVO.getCode())) {
            responseStatusVO.setMessage(type);
        }
        return responseStatusVO;
    }

    @Autowired
    public void setSysConfigService(SysConfigService sysConfigService) {
        this.sysConfigService = sysConfigService;
    }

    @Autowired
    public void setUploadService(UploadService uploadService) {
        this.uploadService = uploadService;
    }
}
